﻿@*
    // Copyright (c) Alex Reich.
    // Licensed under the CC BY 4.0 License.
*@
@using RulesEngineEditor.Models
@inject RulesEngineEditor.Services.WorkflowService WorkflowService

<EditForm EditContext="@EditContext">
    <DataAnnotationsValidator />
    <ValidationSummary />
    <sp_grid_workflow>
        <div>
            <InputText placeholder="Workflow Name" title="Workflow Name" class="form-control" @bind-Value="@Name" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" />
        </div>
        <div>
            <button title="Delete Workflow" @onclick="@(e => DeleteWorkflow())" class="btn btn-secondary">
                <span class="oi oi-trash"></span>
            </button>
        </div>
    </sp_grid_workflow>
</EditForm>
@code {

    private string Name { get { return workFlow.WorkflowName; } set { workFlow.WorkflowName = value; WorkflowService.WorkflowUpdate(); } }

    [Parameter]
    public WorkflowData workFlow { get; set; }

    [Parameter]
    public EventCallback<WorkflowData> WorkflowChanged { get; set; }

    [Parameter]
    public EventCallback<WorkflowData> WorkflowDelete { get; set; }

    [Parameter]
    public EventCallback<WorkflowData> WorkflowCancel { get; set; }

    private EditContext EditContext;

    protected override void OnInitialized()
    {
        EditContext = new EditContext(workFlow);
        EditContext.OnFieldChanged += EditContext_OnFieldChanged;

        base.OnInitialized();
    }

    // Note: The OnFieldChanged event is raised for each field in the model
    private void EditContext_OnFieldChanged(object sender, FieldChangedEventArgs e)
    {
        WorkflowChanged.InvokeAsync(workFlow);
    }

    private void DeleteWorkflow()
    {
        if (workFlow.GlobalParams != null)
            workFlow.GlobalParams.ToList().ForEach(gp => workFlow.GlobalParams.Remove(gp));

        if (workFlow.Rules != null)
            workFlow.Rules.ToList().ForEach(r => WorkflowService.DeleteRule(workFlow, r));

        WorkflowService.Workflows.Remove(workFlow);
        WorkflowService.WorkflowUpdate();
    }
}
